home *** CD-ROM | disk | FTP | other *** search
/ Turnbull China Bikeride / Turnbull China Bikeride - Disc 2.iso / ACORNUSERS / EMULATOR / EMUL6502 / Sources / Factorial < prev    next >
Text File  |  1998-08-27  |  2KB  |  70 lines

  1. ;Alain BROBECKER (aka baah/Arm's Tech), 27aug1998
  2. ;
  3. ;Computes 8!=40320 by using recursive calls. If the result is wrong, it jumps
  4. ;at adress 0 (should contain  &00='brk'), else it ends with the 'brk' inside
  5. ;the code (and you can relax =).
  6.  
  7.             #name       FactorialX
  8.             #list
  9.             #base       &100-4      ;Start assembly here
  10.             #rw         &100        ;Load adress
  11.             #rw         &100        ;Exec adress
  12.  
  13. ;Zero page adresses used as storage
  14. #set        fact = &10
  15. #set        mul1 = &12
  16. #set        mul2 = &13
  17.  
  18.   ldx #&ff              ;Initialise stack
  19.   txs
  20.   ldx #0                ;Initialise z,fact to 7
  21.   stx z,fact+1
  22.   ldx #8
  23.   stx z,fact
  24.   jsr factorial         ;Recursive call with x=7
  25.   lda #&80              ;Compare result with 40320=&9d80
  26.   cmp z,fact
  27.   beq no_error
  28. .error
  29.   jmp 0
  30. .no_error
  31.   lda #&9d
  32.   cmp z,fact+1
  33.   bne error
  34.   brk
  35.  
  36. ;Multiply z,fact with (x-1) and call himself if x-1>1
  37. .factorial
  38.   dex
  39.   cpx #1
  40.   beq factorial_end
  41.   stx z,mul1            ;mul1=x
  42.   lda z,fact            ;mul2=fact
  43.   sta z,mul2
  44.   lda z,fact+1
  45.   sta z,mul2+1
  46.   lda #0                ;fact=0 will contain mul2*mul1
  47.   sta z,fact
  48.   sta z,fact+1
  49.   ldy #8                ;Nb of shift to perform
  50. .shiftmul_one
  51.   lsr z,mul1            ;Carry = shifted bit
  52.   bcc next_shift
  53.   clc                   ;Perform fact+=mul2
  54.   lda z,mul2            ;16 bits addition
  55.   adc z,fact
  56.   sta z,fact
  57.   lda z,mul2+1
  58.   adc z,fact+1
  59.   sta z,fact+1
  60. ;Rotate word in mul2
  61. .next_shift
  62.   asl z,mul2            ;Shift word
  63.   rol z,mul2+1
  64.  dey:bne shiftmul_one
  65.   jsr factorial         ;Recursive call
  66. .factorial_end
  67.   rts
  68.  
  69.  
  70.